<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">


		  <a-col :xl="6" :lg="7" :md="8" :sm="24">
		    <a-form-item label="编号">
		      <a-input  placeholder="请输入编号" v-model="queryParam.dilinniNumber"></a-input>
		    </a-form-item>
		  </a-col>

         <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="状态">
            <a-select
            v-model="queryParam.status"
              style="width: 150px"
              @focus="focus"
              ref="select"
              @change="handleChange"
               placeholder="请选择状态"
            >
              <a-select-option value="0">
                上架中
              </a-select-option>
              <a-select-option value="2" >
                 已下架
              </a-select-option>
            </a-select>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">



          </template>
          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-button type="primary" @click="searchQuery" icon="search" style="color: #F9D532;width: 80px;height: 36px;background: #333333;border-style: none;">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload"  style="color: #F9D532;width: 80px;height: 36px;background: #333333;border-style: none;margin-left: 8px;" >重置</a-button>
               <a-button type="primary" @click="daochu()" icon="download" style="color: #F9D532;width: 80px;height: 36px;background: #333333;border-style: none;margin-left: 8px;" >导出&nbsp;&nbsp;</a-button>

			   <a-upload style="margin-left: 8px" name="file" :showUploadList="false"
			             :multiple="false"
			             :customRequest="myupload"
			             :action="importExcelUrl" @change="handleImportExcel">
			     <a-button type="primary" :loading="ltag" style="color: #F9D532;width: 80px;height: 36px;background: #333333;border-style: none;" icon="import"><upload-outlined/>导入</a-button>
			   </a-upload>

            </a-col>
          </span>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button> -->
      <a-button @click="addCustomerHtml(0)" type="primary" icon="plus" style="color: #F9D532;width: 80px;height: 36px;background: #333333;border-style: none;">新增</a-button>
	  <a-button @click="piliangUpdatestatus(0)" type="primary" style="color: #F9D532;width: 80px;height: 36px;background: #333333;border-style: none;">批量上架</a-button>
	    <a-button @click="piliangUpdatestatus(2)" type="primary" style="color: #F9D532;width: 80px;height: 36px;background: #333333;border-style: none;">批量下架</a-button>
      <!-- <a-button type="primary" icon="download" @click="handleExportXls('单表示例')">导出</a-button> -->
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
      </a-upload>

    </div>


   <a-spin tip="正在导出，请稍等"   v-if="loadingxianshi">
     <div class="spin-content">
     导出Excel文档
     </div>
   </a-spin>

    <a-spin tip="正在操作，请稍等"   v-if="ltag">
      <div class="spin-content">
      导入Excel文档
      </div>
    </a-spin>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

      <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="30px" alt=""
               style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>

        <div slot="filterDropdown">
          <a-card>
            <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
              <a-row>
                <template v-for="(item,index) in defColumns">
                  <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                    <a-col :span="12"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                  </template>
                </template>
              </a-row>
            </a-checkbox-group>
          </a-card>
        </div>
        <a-icon slot="filterIcon" type='setting' :style="{ fontSize:'16px',color:  '#108ee9' }" />

        <span slot="action" slot-scope="text, record">
           <a @click="getBackCustDetail(record.id,record.realname)">查看详情</a>&nbsp;
          <a @click="addCustomerHtml(record.id)">编辑</a>&nbsp;
           <a v-if="record.status==0" @click="custstop(record.id,2)">下架</a>&nbsp;
            <a v-if="record.status==2" @click="custstop(record.id,0)">启用</a>&nbsp;
            <a-popconfirm title="确定删除吗?" @confirm="() => custstop(record.id,1)">
                 <a>删除</a>
                </a-popconfirm>

        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <jeecgDemo-modal ref="modalForm" @ok="modalFormOk"></jeecgDemo-modal>

    <!-- 一对多表单区域 -->
    <JeecgDemoTabsModal ref="jeecgDemoTabsModal" @ok="modalFormOk"></JeecgDemoTabsModal>

  <div>
     <a-drawer width="500" placement="right" :closable="false" :visible="visible" @close="onClose">
    <!-- <p :style="[pStyle, pStyle2]">
      User Profile
    </p> -->
    <p :style="pStyle">
      底领呢基本信息
    </p>
    <a-row>
      <a-col :span="20">

              <table>
            <tr class="mytr">
							底领呢图片
  		 <img :src="this.xiangqingdetail.img"  style="width: 150px;height: 150px;"/>

            </tr>
           <!-- <tr class="mytr">
              <td class="fatitle">底领呢名称</td>
              <td class="facontent">{{this.xiangqingdetail.dilinniName}}</td>
              <td class="fatitle">库存</td>
              <td class="facontent">{{this.xiangqingdetail.inventory}}</td>
            </tr> -->

          </table>
      </a-col>
    </a-row>

    <a-divider />


    <p :style="pStyle">
      基本信息
    </p>
    <a-row>
      <a-col :span="20">
           <table>

			   <tr class="mytr">
			     <td class="fatitle">底领呢编号</td>
			     <td class="facontent">{{this.xiangqingdetail.dilinniNumber}}</td>
			   </tr>

			   <tr class="mytr">
			     <td class="fatitle">供应商</td>
			     <td class="facontent">{{this.xiangqingdetail.realname}}</td>
			   </tr>

            <tr class="mytr">
              <td class="fatitle">售价加价</td>
              <td class="facontent">{{this.xiangqingdetail.salesPrice}}</td>
            </tr>

         <tr class="mytr">
               <td class="fatitle">成本加价</td>
              <td class="facontent">{{this.xiangqingdetail.costPrice}}</td>
            </tr>

  		<tr class="mytr">
  		      <td class="fatitle">销售状态</td>
  		    <td class="facontent" v-if="this.xiangqingdetail.status==0">上架中</td>
  		    <td class="facontent" v-if="this.xiangqingdetail.status==2">停售</td>
  		   </tr>
  		   <tr class="mytr">
  		         <td class="fatitle">备注</td>
  		    <!--    <td class="facontent">{{this.xiangqingdetail.remark}}</td> -->
				<a-textarea disabled=true :rows="4"  v-model="this.xiangqingdetail.remark" style="width: 300px;"/>
  		      </tr>
          </table>
      </a-col>

    </a-row>

  </a-drawer>

   </div>

  </a-card>
</template>

<script>
 import JeecgDemoModal from './modules/JeecgDemoModal'
  import JSuperQuery from '@/components/jeecg/JSuperQuery.vue';
  import JInput from '@/components/jeecg/JInput.vue';
  import {initDictOptions, filterDictText,filterDictTextByCache} from '@/components/dict/JDictSelectUtil'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import Vue from 'vue'
  import { filterObj } from '@/utils/util';
  import {postAction,deleteAction, getAction,downFile,getFileAccessHttpUrl } from '@/api/manage'


  //高级查询modal需要参数
  const superQueryFieldList=[
    {
      type: "string",
      value: "name",
      text: "用户名"
    }, {
      type: "int",
      value: "age",
      text: "年龄"
    }, {
      type: "date",
      value: "birthday",
      text: "生日"
    }
  ]
  export default {
    name: "DilinniManage",
    mixins:[JeecgListMixin],
    components: {
      JeecgDemoModal,
      JSuperQuery,

      JInput
    },
    data() {
      return {
		  ltag:false,
				 loadingxianshi:false,
    ids:[],
				/* table选中keys*/
				selectedRowKeys: [],
				 /* table选中record*/
				  selectionRows: [],
       xiangqingdetail:{

       },

        //这里是给弹框用的
          visible: false,
      pStyle: {
        fontSize: '16px',
        color: 'rgba(0,0,0,0.85)',
        lineHeight: '24px',
        display: 'block',
        marginBottom: '16px',
      },
      pStyle2: {
        marginBottom: '24px',
      },


        customerDetail:[],
        description: '单表示例列表',
        //字典数组缓存
        sexDictOptions: [],
        importExcelUrl:`${window._CONFIG['domianURL']}/test/jeecgDemo/importExcel`,
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        //列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '编号',
            align: "center",
            dataIndex: 'dilinniNumber'
          },
          {
            title: '供应商',
            align: "center",
            dataIndex: 'realname'
          },
          {
            title: '缩略图',
            align: "center",
            dataIndex: 'img',
			scopedSlots: {customRender: 'imgSlot'}
          },
		  // {
		  //   title: '名称',
		  //   align: "center",
		  //   dataIndex: 'dilinniName'
		  // },
		  {
		    title: '售价加价',
		    align: "center",
		    dataIndex: 'salesPrice'
		  },
		  {
		    title: '成本加价',
		    align: "center",
		    dataIndex: 'costPrice'
		  },


		  // {
		  //   title: '库存',
		  //   align: "center",
		  //   dataIndex: 'inventory'
		  // },
          {
            title: '销售状态',
            align: "center",
            dataIndex: 'status',
            customRender: (status) => {
              //字典值替换通用方法
              if(status==0)
              return "上架中";
              else
              return "已下架";
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action'},
          }
        ],
        url: {
          list: "/DilinniManage/DilinniList",
          delete: "/DilinniManage/updateDilinnistatus",
          deleteBatch: "/test/jeecgDemo/deleteBatch",
          exportXlsUrl: "/DilinniManage/downloadDilinni",
          detail:"/DilinniManage/getDilinnibyId",
					  piliangUpdatestatus:"/DilinniManage/piliangUpdatestatus",
					    importExcelUrl: "/DilinniManage/importExcel", // 导入Excel
        },
        fieldList:superQueryFieldList
      }
    },
    methods: {
		daochu(){
			this.loadingxianshi=true;

			this.handleExportXls3('底领呢列表');
		},

		handleExportXls3(fileName){
		  if(!fileName || typeof fileName != "string"){
		    fileName = "导出文件"
		  }
		  let param = {...this.queryParam};
		  if(this.selectedRowKeys && this.selectedRowKeys.length>0){
		    param['selections'] = this.selectedRowKeys.join(",")
		  }
		  downFile(this.url.exportXlsUrl,param).then((data)=>{
		    if (!data) {
		      this.$message.warning("文件下载失败")
		      return
		    }
		    if (typeof window.navigator.msSaveBlob !== 'undefined') {
		      window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
		    }else{
		      let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
		      let link = document.createElement('a')
		      link.style.display = 'none'
		      link.href = url
		      link.setAttribute('download', fileName+'.xls')
		      document.body.appendChild(link)
		      link.click()
		      document.body.removeChild(link); //下载完成移除元素
		      window.URL.revokeObjectURL(url); //释放掉blob对象
		    }
				this.loadingxianshi=false;
		  })
		},


		// 导入纽扣excel
		myupload(data) {
				this.ltag=true;
		  let fdata = new FormData()
		  fdata.append('file', data.file)

		  postAction(this.url.importExcelUrl, fdata).then(res => {
		    this.$message.success(res.message);
		     this.loadData();
			 	this.ltag=false;
		  })
		},
		onSelectChange(selectedRowKeys, selectionRows) {
		  this.selectedRowKeys = selectedRowKeys;

		  this.selectionRows = selectionRows;
		    for (var i=0;i<this.selectionRows.length;i++)
		     {
		          this.ids.push(this.selectionRows[i].id);
		          console.log("看一看能不能成功"+this.ids[i]);
		     }
		},

		piliangUpdatestatus(status){
		postAction(this.url.piliangUpdatestatus,{status:status,ids:this.ids}).then((res)=>{
		   if (res.success) {
		    		  this.$message.success(res.message);
					  this.ids=[];
					   this.selectedRowKeys=[];
					     this.selectionRows=[];
				    this.loadData();
		       } else {
		         this.$message.warning(res.message);
		       }
		     });
			},

    //跳到新增用户的界面去
       addCustomerHtml(id){

	   if(id==0){
		    this.$router.push({path:'/addDilinni',query: {id:id}})
	   }else{
		  this.$router.push({path:'/updateDilinni',query: {id:id}})
	   }

      },
    showDrawer() {
      this.visible = true;
    },
    onClose() {
      this.visible = false;
    },

    //获取客户详情信息的方法
    getBackCustDetail(id,realname){
         this.visible = true;
       console.log("看看进来了吗");
       getAction(this.url.detail,{id: id}).then((res)=>{
          if (res.success) {
              this.xiangqingdetail=res.result;
			   this.xiangqingdetail.realname=realname;

              } else {
                that.$message.warning(res.message);
              }
            });
    },


     //编辑或者停用
     custstop(id,status){
       var that=this;

         getAction(that.url.delete, {id: id,status:status}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.loading = false;
            });
     },

      getQueryParams(){
        //高级查询器
        let sqp = {}
        if(this.superQueryParams){
          sqp['superQueryParams']=encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);

        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        delete param.birthdayRange; //范围参数不传递后台
        return filterObj(param);
      },
      initDictConfig() {
        console.log("--我才是真的方法!--")
        //初始化字典 - 性别
        initDictOptions('sex').then((res) => {
          if (res.success) {
            this.sexDictOptions = res.result;
          }
        });
      },
      onetomany: function () {
        this.$refs.jeecgDemoTabsModal.add();
        this.$refs.jeecgDemoTabsModal.title = "编辑";
      },
      //跳转单据页面
      jump() {
        this.$router.push({path: '/jeecg/helloworld'})
      },
      onBirthdayChange: function (value, dateString) {
        console.log(dateString[0],dateString[1]);
        this.queryParam.birthday_begin=dateString[0];
        this.queryParam.birthday_end=dateString[1];
      },
      //列设置更改事件
      onColSettingsChange (checkedValues) {
        var key = this.$route.name+":colsettings";
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues;
        const cols = this.defColumns.filter(item => {
          if(item.key =='rowIndex'|| item.dataIndex=='action'){
            return true
          }
          if (this.settingColumns.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns =  cols;
      },
      initColumns(){
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name+":colsettings";
        let colSettings= Vue.ls.get(key);
        if(colSettings==null||colSettings==undefined){
          let allSettingColumns = [];
          this.defColumns.forEach(function (item,i,array ) {
            allSettingColumns.push(item.dataIndex);
          })
          this.settingColumns = allSettingColumns;
          this.columns = this.defColumns;
        }else{
          this.settingColumns = colSettings;
          const cols = this.defColumns.filter(item => {
            if(item.key =='rowIndex'|| item.dataIndex=='action'){
              return true;
            }
            if (colSettings.includes(item.dataIndex)) {
              return true;
            }
            return false;
          })
          this.columns =  cols;
        }
      }
    },
    created() {
      this.initColumns();
    },
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  .spin-content {
    border: 1px solid #91d5ff;
    background-color: #e6f7ff;
    padding: 30px;
  }
    .fatitle {
    height: 34px;
    width: 82px;
    background: rgb(242 242 242);
    text-align: center;
  }

  .facontent {
    width: 180px;
    overflow: hidden;
    text-align: center;
  }
</style>